package com.qunar.wan.util;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.io.StringWriter;
import java.util.Map;
import java.util.Properties;

/**
 * User: cyoung Date: 11/29/13 Time: 1:27 PM
 */

public class VelocityUtil {
    private VelocityUtil() {
    }

    static Logger logger = LoggerFactory.getLogger(VelocityUtil.class);

    static VelocityEngine engine = null;

    static {
        Properties p = new Properties();
        InputStream is = null;
        try {
            is = VelocityUtil.class.getResourceAsStream("/velocity.properties");
            p.load(is);
            engine = new VelocityEngine(p);
        } catch (Exception e) {
            throw new RuntimeException("init velocityutl", e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    logger.error("", e);
                }
            }
        }
    }

    /**
     * 解析模板内容
     * 
     * @param templatePath 模板路径，基于classpath
     * @param contextMap 上下文变量
     * @return 解析完的内容
     */
    public static String getRenderResult(String templatePath, Map<String, Object> contextMap) {
        Template template = engine.getTemplate(templatePath, "UTF-8");
        Context context = new VelocityContext(contextMap);
        StringWriter writer = new StringWriter();
        template.merge(context, writer);
        return writer.toString();
    }

    /**
     * 解析模板内容
     * 
     * @param templateContent 模板内容
     * @param contextMap 上下文变量
     * @param key 模板KEY值
     * @return 解析完的内容
     */
    public static String getRenderResult(String templateContent, Map<String, Object> contextMap, String key) {
        Context context = new VelocityContext(contextMap);
        StringWriter writer = new StringWriter();
        engine.evaluate(context, writer, key, templateContent);
        return writer.toString();
    }

}
